<?php
namespace app\manage\controller;
use app\manage\controller\Conn;
use app\manage\model\Goods as Goodsmodel;
use app\manage\model\Category as Categorymodel;
use \think\Loader;
use think\Db;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

use QL\QueryList;
class Goods extends Conn
{
    public function index()
    {

		$key=input('key') ? input('key') : '';
		$this->assign('key',$key);
		
		$goodsRes=Db::name('goods')->where('goods_name','like','%'.$key.'%')->order('id DESC')->paginate(10,false,['query'=>request()->param()])->each(function($item, $key){
			$item['cate_id'] = Db::name('goods_cate')->where('id',$item['cate_id'])->value('name') ?? '其他';
			return $item;
		});;
		$this->assign(['goodsRes'=>$goodsRes]);
		
		$count1=Db::name('goods')->count();
		$this->assign('count1', $count1);
       	return $this->fetch();
    }
	public function ajax()
    {
    	$data=input('param.');
		//下面是删除
		if($data['type']=='goods_del'){
			$id=$data['id'];
			if(model('goods')->destroy($id)){
				return 1;//修改成功返回1
			}else{
				return 0;
			}
		}
		
		if($data['type']=='attr_del'){
			if($w=Db::name('goods_attr')->where('goods_id',$data['id'])->find()){
				Db::name('goods_attr')->delete($w['id']);
				return 1;//修改成功返回1
			}
			return 0;//修改成功返回1
			
		}
		
		//下面两个是商品的启用和停止
		if($data['type']=='goods_start'){
			if(Db::name('goods')->where('id',$data['id'])->setField('isopen',1)){
				return 1;//修改成功返回1
			}else{
				return 0;
			}
		}
       	if($data['type']=='goods_stop'){
			if(Db::name('goods')->where('id',$data['id'])->setField('isopen',0)){
				return 1;//修改成功返回1
			}else{
				return 0;
			}
		}
		//下面两个是商品的启用和停止
		if($data['type']=='goods_she'){
			if(Db::name('goods')->where('id',$data['id'])->setField('is_tui',1)){
				return 1;//修改成功返回1
			}else{
				return 0;
			}
		}
		if($data['type']=='goods_che'){
			if(Db::name('goods')->where('id',$data['id'])->setField('is_tui',0)){
				return 1;//修改成功返回1
			}else{
				return 0;
			}
		}
		
		if($data['type']=='goods_baihui'){ //当当 http://product.dangdang.com
			if (filter_var($data['url'], FILTER_VALIDATE_URL) !== false) {
				$tempu=parse_url($data['url']);
				$message=$tempu['host'];
				if($message!="product.dangdang.com"){
					return ['code'=>0,'msg'=>'请抓取当当域名不正确'];
				}
				parse_str($tempu["query"],$query_arr);
				$url="http://by.bhyyoumei.com/ItemApi/detail?page=1&id=".$query_arr['detailId']."&no_group=1&sid=".$query_arr['sid']."&pid=0";
				$html = file_get_contents($url);
				$html=\json_decode($html,true);
				if(isset($html['data']["item_detail"]["img_path"])){
					return ['code'=>1,'msg'=>'成功','data'=>$html['data']["item_detail"]["img_path"]];
				}else{
					return ['code'=>0,'msg'=>'抓取错误'];
				}
			}else{
				return ['code'=>0,'msg'=>'url地址不正确'];
			}
		}
		
		if($data['type']=='goods_zhua'){
			if (filter_var($data['url'], FILTER_VALIDATE_URL) !== false) {
				$tempu=parse_url($data['url']);
				$message=$tempu['host'];
				if(substr($message,-6)!='jd.com'){
					return ['code'=>0,'msg'=>'请抓取京东数据'];
				}
				
				$html = QueryList::get($data['url'])->find('html')->html();
//                preg_match("/src:'\w*',/", $html, $match3);
//				dump($match3);
//				dump(1111);
//                dump($html);
				preg_match("/mainSkuId:'\d*', /", $html, $match1);
				preg_match("/data-id=\"\d*\"/", $html, $match2);
				if(!\is_array($match1) or !\is_array($match2)){
					return ['code'=>0,'msg'=>'抓取错误'];
				}
				preg_match('/\d+/',$match1[0],$mainSkuId);
				preg_match('/\d+/',$match2[0],$skuId);
				$mainSkuId=$mainSkuId[0];
				$skuId=$skuId[0];
				if($mainSkuId and $skuId){
					$url="https://cd.jd.com/description/channel?skuId=$skuId&mainSkuId=$mainSkuId&charset=utf-8&cdn=2&callback=showdesc";
					$desc= file_get_contents($url);
					$h=json_decode(substr($desc,9,-1),true)["content"];
					$ql = QueryList::html($h);
					$w=$ql->find('img')->attrs('data-lazyload');
					$array =  json_decode( json_encode( $w),true);
					if(empty($array)){
						preg_match_all("/(\/\/img30.360buyimg.com\/\S*)/", $h, $wo);
						if(isset($wo[0])){
							$a=[];
							foreach($wo[0] as $v){
								$a[]=substr($v,0,-2);
							}
							$array=$a;
						}
					}
					return ['code'=>1,'msg'=>'成功','data'=>$array];
				}else{
					return ['code'=>0,'msg'=>'抓取错误'];
				}

			}else{
				return ['code'=>0,'msg'=>'url地址不正确'];
			}
		}
		
		return 0;
    }
	public function add()
    {
    	if(request()->isPost()){
    		$data=input('post.');
			$validate = new \app\manage\validate\Goods;
			if (!$validate->check($data)) {
			    $this->error($validate->getError());
			}
			if($data['fen_money'] > $data['money'] *0.95){
				$this->error('分润不能超过价格的95%！');
			}
			$file = request()->file();
			if(!isset($file['goods_img'])){
				$this->error('请添加首页主图！');
			}
// 			if(!isset($file['goods_list_img'])){
// 				$this->error('请添加详情主图！');
// 			}

			if (!isset($data['isopen'])) {
			    $data['isopen']=0;
			} else {
			    $data['isopen']=1;
			}

			$data['goods_code']=time().rand(111111,999999);//商品编号
            $file = request()->file('');
            if (isset($file['goods_img'])) {
                $info = $file['goods_img']->move('uploads');
                $li=strtr($info->getSaveName(), " \ ", " / ");
                $data['goods_img']='/uploads/'.$li;
            }
            if (isset($file['goods_list_img'])) {
                $info = $file['goods_list_img']->move('uploads');
                $li=strtr($info->getSaveName(), " \ ", " / ");
                $data['goods_list_img']='/uploads/'.$li;
            }

			$goods = new goodsmodel();
			if($goods->allowField(true)->save($data)){
				$attr_value=str_replace(" ",'',$data['attr_value']);
				$attr_value=str_replace("，", ",", $attr_value);
				$attr_value=implode(",", array_filter(explode(",", $attr_value)));
				
				$attr_title=$data['attr_title'];
				if($attr_title and $attr_value){
					if($w=Db::name('goods_attr')->where('goods_id',$goods->id)->find()){
						Db::name('goods_attr')->where('id',$w['id'])->update([
							'title'=>$attr_title,
							'value'=>$attr_value,
						]);
					}else{
						Db::name('goods_attr')->insert([
							'goods_id'=>$goods->id,
							'title'=>$attr_title,
							'value'=>$attr_value,
						]);
					}
				}
				$this->success('添加成功了');
			}else{
				$this->error('添加失败了');
			}
    	}
		$this->assign('cate',Db::name('goods_cate')->where('isopen',1)->order('sort asc')->select());
		
		
      	return $this->fetch();
    }
	public function edit()
    {
    	$id=input('id');
		
    	if(request()->isPost()){
    		$data=input('post.');
			
			$validate = new \app\manage\validate\Goods;
			if (!$validate->scene('edit')->check($data)) {
			    $this->error($validate->getError());
			}
			if($data['fen_money'] > $data['money'] *0.95){
				$this->error('分润不能超过价格的95%！');
			}
			
			$file = request()->file();
            if (isset($file['goods_img'])) {
                $info = $file['goods_img']->move('uploads');
                $li=strtr($info->getSaveName(), " \ ", " / ");
                $data['goods_img']='/uploads/'.$li;
            }
            if (isset($file['goods_list_img'])) {
                $info = $file['goods_list_img']->move('uploads');
                $li=strtr($info->getSaveName(), " \ ", " / ");
                $data['goods_list_img']='/uploads/'.$li;
            }
			
			if (!isset($data['isopen'])) {
			    $data['isopen']=0;
			} else {
			    $data['isopen']=1;
			}
			$goods = new goodsmodel();
			if($goods->allowField(true)->save($data,['id' => $id])){
				
				$attr_value=str_replace(" ",'',$data['attr_value']);
				$attr_value=str_replace("，", ",", $attr_value);
				$attr_value=implode(",", array_filter(explode(",", $attr_value)));
				$attr_title=$data['attr_title'];
				if($attr_title and $attr_value){
					if($w=Db::name('goods_attr')->where('goods_id',$id)->find()){
						Db::name('goods_attr')->where('id',$w['id'])->update([
							'title'=>$attr_title,
							'value'=>$attr_value,
						]);
					}else{
						Db::name('goods_attr')->insert([
							'goods_id'=>$id,
							'title'=>$attr_title,
							'value'=>$attr_value,
						]);
					}
				}
				

				
				$this->success('修改成功了');
			}else{
				$this->error('修改失败了');
			}
    	}
		// 查询当前商品基本信息
        $goods=db('goods')->find($id);
		$this->assign('goods',$goods);
		$this->assign('attr',Db::name('goods_attr')->where('goods_id',$id)->find());
		$this->assign('cate',Db::name('goods_cate')->where('isopen',1)->order('sort asc')->select());
      	return $this->fetch();
    }
	

}
